package com.spring.test.interceptor;

import com.spring.test.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断用户是否登录 (判断session中是否有user)

        HttpSession session = request.getSession();

        User user = (User) session.getAttribute("user");

        if (user == null) {

            //没有登录信息 跳转到登录界面

            response.sendRedirect(request.getContextPath() + "/login.jsp");

            return false;

        }

        //有登录信息 放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
